package com.bloog.zxingteste;

import java.io.File;
import java.util.Locale;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents.Encode;
import com.google.zxing.client.android.Intents.Scan;
import com.google.zxing.client.android.bloog.CaptureActivityFragment;
import com.google.zxing.client.android.bloog.OnCaptureDecodedListener;
import com.google.zxing.client.android.encode.QRCodeEncoder;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;

@EActivity(R.layout.main)
public class MainActivity extends FragmentActivity implements OnInitListener, OnCaptureDecodedListener {

    //TTS object
	private TextToSpeech myTTS;
    //status check code
	private int TTS_CODE = 0;
	private int SCAN_CODE = 1;
	private Fragment caFrag = null;
	
	@ViewById EditText edContent;
	@ViewById Button btLer;
	@ViewById Button btScan;
	@ViewById Button btQRCode;
	@ViewById ImageView imgQRCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        initTTS();
    }

    @Click
    public void btTeste(){
    	if(caFrag == null){
	    	caFrag = new CaptureActivityFragment();
	    	Intent intent = new Intent(Scan.ACTION);
	    	intent.putExtra(Scan.MODE, Scan.QR_CODE_MODE);
	    	caFrag.setArguments(intent.getExtras());
	    	getSupportFragmentManager().beginTransaction().replace(R.id.fgView, caFrag).commit();
    	}else{
    		View fgView = findViewById(R.id.fgView);
    		if(fgView.getVisibility() == View.VISIBLE)
    			fgView.setVisibility(View.GONE);
    		else
    			fgView.setVisibility(View.VISIBLE);
    	}
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(myTTS != null){
			while(myTTS.isSpeaking())
				try {
					wait(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			myTTS.stop();
			myTTS.shutdown();
		}
		super.onDestroy();
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

	@Click
	public void btScan(){
    	Intent intent = new Intent(Scan.ACTION);
    	intent.putExtra(Scan.MODE, Scan.QR_CODE_MODE);
    	startActivityForResult(intent, SCAN_CODE);	
	}

	@Click
	public void btQRCode(){
		Intent intent = new Intent(Encode.ACTION);
		intent.putExtra(Encode.TYPE, Contents.Type.TEXT);
		intent.putExtra(Encode.DATA, edContent.getText().toString());
		intent.putExtra(Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
//    	startActivity(intent);	
	    gerarQRCode(intent);
	}

	@Click
	public void btLer(){
//		speakWords(edContent.getText().toString());
	}
	
	@SuppressWarnings("deprecation")
	private void gerarQRCode(Intent intent) {
		// This assumes the view is full screen, which is a good assumption
		WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		int smallerDimension = width < height ? width : height;
		smallerDimension = smallerDimension * 7 / 8;

		QRCodeEncoder qrCodeEncoder;
		try {
			qrCodeEncoder = new QRCodeEncoder(this, intent, smallerDimension, false);
		    Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
		    imgQRCode.setImageBitmap(bitmap);
		    Toast.makeText(getApplicationContext(), getString(R.string.gerado), Toast.LENGTH_SHORT).show();
		} catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//speak the user text
	public void speakWords(String texto) { 
	        //speak straight away
//		if(myTTS != null)
//	        myTTS.speak(texto, TextToSpeech.QUEUE_FLUSH, null);
	}
	
	private void initTTS() {
		//check for TTS data
	    Intent checkTTSIntent = new Intent();
	    checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
	    startActivityForResult(checkTTSIntent, TTS_CODE);
	}
//    
//	private void initPreview() {
//		Camera camera = Camera.open();
//    	try {
//    		preview_view.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//			camera.setPreviewDisplay(preview_view.getHolder());
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//    	camera.startPreview();
//	}    

    //setup TTS
	public void onInit(int initStatus) {     
	        //check for successful instantiation
	    if (initStatus == TextToSpeech.SUCCESS) {
	        if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
	            myTTS.setLanguage(Locale.US);
	    }
	    else if (initStatus == TextToSpeech.ERROR) {
	        Toast.makeText(getApplicationContext(), "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
	    }
	}

	    //act on result of TTS data check
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {     
	    if (requestCode == TTS_CODE)
	        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
	            //the user has the necessary data - create the TTS
	        	myTTS = new TextToSpeech(this, this);
	        }
	        else {
	                //no data - install it now
	            Intent installTTSIntent = new Intent();
	            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
	            startActivity(installTTSIntent);
	        }   
	    //SCAN
		if (requestCode == SCAN_CODE)
			if(resultCode == RESULT_OK){
				String conteudo = data.getStringExtra(Scan.RESULT);
				String formato = data.getStringExtra(Scan.RESULT_FORMAT);
				String resultado = getString(R.string.leitura_ok) + "\n" + getString(R.string.dados_)
									+ conteudo + "\n" + getString(R.string.formato_) + formato;
				Toast.makeText(getApplicationContext(), resultado, Toast.LENGTH_LONG).show();
				edContent.setText(conteudo);
				btQRCode();
				if(conteudo.endsWith(".mp4")){
					File arq = new File(Environment.getExternalStorageDirectory().getPath() + "/Bloog/" + conteudo);
					edContent.setText(Environment.getExternalStorageDirectory().getPath() + "/Bloog/" + conteudo);
					Uri video = Uri.fromFile(arq);
					Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setDataAndType(video, "video/*"); //Uri.parse(arq.getPath())
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
				}else					
					btLer();
			}else if(resultCode == RESULT_CANCELED){
				Toast.makeText(getApplicationContext(), R.string.leitura_cancelada, Toast.LENGTH_LONG).show();
				edContent.setText("");
			}
	}

	@Override
	public void onCaptureDecoded(String qrcode) {
		edContent.setText(qrcode);
		Toast.makeText(getApplicationContext(), R.string.leitura_ok, Toast.LENGTH_LONG).show();
	}
	
}
